package com.hxzy.tms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hxzy.tms.dao.BaseDao.Params;
import com.hxzy.tms.dao.ProjectDao;
import com.hxzy.tms.dao.TeamDao;
import com.hxzy.tms.dao.TeamUserDao;
import com.hxzy.tms.dao.UserDao;
import com.hxzy.tms.entity.Project;
import com.hxzy.tms.entity.Team;
import com.hxzy.tms.entity.TeamUser;
import com.hxzy.tms.entity.User;
import com.hxzy.tms.service.ProjectService;
import com.hxzy.tms.service.ServiceResult;
import com.hxzy.tms.service.TeamService;
import com.hxzy.tms.service.TeamUserService;
import com.hxzy.tms.service.UserService;
import com.hxzy.tms.session.SessionHolder;
import com.mysql.fabric.xmlrpc.base.Param;

public class TeamServiceImpl implements TeamService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private TeamDao teamDao;
    private TeamService teamService;
    private TeamUserDao teamUserDao;
    private TeamUserService teamUserService;
    private ProjectDao projectDao;
    private ProjectService projectService;
    private UserDao userDao;
    private UserService userService;
    
    //分页查询
    public List<Team> myTeam(Long uidCreate,int arg1,int arg2){
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("uidCreate", uidCreate);
            List<Team> myTeamList = teamDao.read("from Team where uidCreate.id = :uidCreate", param,arg1,arg2);
            return myTeamList;
    }
    
    public int count(long uidCreate) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("uidCreate", uidCreate);
        List<Team> teamList = teamDao.read("from Team where uidCreate.id=:uidCreate", param);
        int count = teamList.size();
        return count;
    }
    //我的团队
    public ServiceResult<List<Team>> myLists(Long status) {
        if (SessionHolder.get() == null) {
            return new ServiceResult<List<Team>>(-1,null,"用户未登录不能创建团队");
        }
        List<Params> params=new ArrayList<Params>();
        String sql="from Team where uidCreate.id = :user_id";
        params.add(new Params("user_id",SessionHolder.get().getId()));
        if(status!=null){
        	sql+=" and status =:status";
        	params.add(new Params("status", status));
        }
        sql+=" order by gmtCreate desc";
        List<Team> teamList=teamDao.read(sql, params);
        return new ServiceResult<List<Team>>(1, teamList);
    }
    
    public ServiceResult<Team> update(long id, String name, String desc, String intro, String subdomain, Date gmtBegin,
            Date gmtEnd) {
        if (SessionHolder.get() == null) {
        	return new ServiceResult<Team>(-1,null,"用户未登录不能创建团队");
        }
        if (StringUtils.isBlank(name) || StringUtils.isBlank(desc) || StringUtils.isBlank(intro) || 
                StringUtils.isBlank(subdomain) || gmtBegin.equals(" ") || gmtEnd.equals(" ")) {
        	return new ServiceResult<Team>(-2,null,"输入项不能为空");
        }
        return teamService.saveOrUpdate(id, name, desc, intro, subdomain, gmtBegin, gmtEnd);
    }

    public ServiceResult<Team> create(String name, String desc, String intro, String subdomain, Date gmtBegin,
            Date gmtEnd) {
        if (SessionHolder.get().getId() == null) {
            return new ServiceResult<Team>(-1,null,"用户未登录不能创建团队");
        }
        if (StringUtils.isBlank(name) || StringUtils.isBlank(desc) || StringUtils.isBlank(intro) || 
                StringUtils.isBlank(subdomain) || gmtBegin.equals(" ") || gmtEnd.equals(" ")) {
        	return new ServiceResult<Team>(-2,null,"输入项不能为空");
        }
        
        return teamService.saveOrUpdate(null,name, desc, intro, subdomain, gmtBegin, gmtEnd);
    }
    
    public ServiceResult<Team> saveOrUpdate(Long id,String name, String desc, String intro, String subdomain,
            Date gmtBegin, Date gmtEnd) {
        if (gmtEnd.getTime() < gmtBegin.getTime()) {
        	return new ServiceResult<Team>(-1,null,"开始时间应大于结束时间");
        }
        if (gmtBegin.equals(gmtEnd)) {
            return new ServiceResult<Team>(-1,null,"开始日期和结束日期不能相同");
        }
        List<Team> teams = new ArrayList<Team>();
        if (id != null) {
            teams = teamDao.read("from Team where name =:name and id !=:id", new Params("name",name),new Params("id", id));
        } else {
            teams = teamDao.read("from Team where name =:name", new Params("name",name));
        }
        if (!teams.isEmpty()) {
            return new ServiceResult<Team>(-1,null,"已有相同名字的团队");
        }
        if (id != null) {
            teams = teamDao.read("from Team where subdomain =:subdomain and id !=:id", new Params("subdomain",subdomain),new Params("id", id));
        } else {
            teams = teamDao.read("from Team where subdomain =:subdomain", new Params("subdomain",subdomain));
        }
        if (!teams.isEmpty()) {
            return new ServiceResult<Team>(-1,null,"二级域名已被注册，请更换二级域名");
        }
        Team team = new Team();
        team.setName(name);
        team.setDesc(desc);
        team.setSubdomain(subdomain);
        team.setIntro(intro);
        team.setStatus(1L);
        team.setUidCreate(SessionHolder.get());
        team.setUidModified(SessionHolder.get());
        team.setGmtBegin(gmtBegin.getTime()/1000);
        team.setGmtEnd(gmtEnd.getTime()/1000);
        team.setGmtCreate(System.currentTimeMillis()/1000);
        team.setUserCount(10L);
        team.setGmtModified(0L);
        
        if (id != null) {
            team.setId(id);
            teamDao.update(team);
        } else {
            teamDao.create(team);
        }
        return new ServiceResult<Team>(1, team);
    }
    //查询团队
    public List<Team> list(Integer status) {
    	List<Team> teamList=teamDao.read("from Team where 1=:status", new Params("status",status));
        return teamList;
    }
    
    
    //团队成员列表
    public ServiceResult<List<User>> memberList(Long teamId){
    	List<User> memberList=teamUserDao.teamUsers(teamId);
    	return new ServiceResult<List<User>>(1,memberList);
    }
    //团队项目列表
    public  ServiceResult<List<Project>> projectList(Long teamId){
    	List<Project> projectList=projectDao.read("from Project where team.id=:teamId", new Params("teamId", teamId));
    	return new ServiceResult<List<Project>>(1,projectList);
    }
    //邀请成员
    public int invite(long uid, long teamId, String email) {
    	if(uid<=0){
    		throw new IllegalArgumentException("uid must more than or equal 0");
    	}
    	if(teamId<=0){
    		throw new IllegalArgumentException("team id must more than or equal 0");
    	}
    	if(StringUtils.isBlank(email)){
    		throw new IllegalArgumentException("email is null or empty");
    	}
    	
    	List<User> userList=userDao.read("from User where email =:email", new Params("email", email));
    	User user=userList.get(0);
    	if(user.getId()==uid){
    		return -1;//判断用户是否邀请的自己
    	}
    	List<TeamUser> teamList=teamUserDao.read("from TeamUser where user.id=:uid and team.id=:teamId",new Params("uid", user.getId()),new Params("teamId", teamId) );
    	if(!teamList.isEmpty()){
    		return -2;//用户已存在
    	}
    	Team team=teamDao.read(Team.class,teamId);
    	
    	if(!team.getUidCreate().getId().equals(uid)){
    		return -3;//不是团队创建者，不能邀请用户
    	}
    	if(!userList.isEmpty()){
    		TeamUser teamUser=new TeamUser();
    		teamUser.setTeam(teamDao.read(Team.class, teamId));
    		teamUser.setUidCreate(SessionHolder.get());
    		teamUser.setStatus(1L);
    		teamUser.setUserNickname(user.getNickname());
    		teamUser.setUser(user);
    		teamUser.setGmtCreate(System.currentTimeMillis()/1000);
    		teamUserDao.create(teamUser);
    	}else{
    		return -4;//email 对应用户不存在
    	}
        return 1;
    }

    public ServiceResult<Team> read(long id) {
        Team team = teamDao.read(Team.class,id);
        return new ServiceResult<Team>(1,team);
    }
    
    
	public ProjectDao getProjectDao() {
		return projectDao;
	}

	public void setProjectDao(ProjectDao projectDao) {
		this.projectDao = projectDao;
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public TeamUserDao getTeamUserDao() {
		return teamUserDao;
	}

	public void setTeamUserDao(TeamUserDao teamUserDao) {
		this.teamUserDao = teamUserDao;
	}

	public TeamUserService getTeamUserService() {
		return teamUserService;
	}

	public void setTeamUserService(TeamUserService teamUserService) {
		this.teamUserService = teamUserService;
	}

	public TeamDao getTeamDao() {
        return teamDao;
    }

    public void setTeamDao(TeamDao teamDao) {
        this.teamDao = teamDao;
    }

    public TeamService getTeamService() {
        return teamService;
    }

    public void setTeamService(TeamService teamService) {
        this.teamService = teamService;
    }
}
